﻿/******************************************************************* 
* Copyright (C)  版权所有
* 创建时间:2019/4/29 15:05:49
* 作    者: zhenhua.shen
* 邮    箱：1025556487@qq.com
* 描    述：实现枚举列表类型的json序列号与反序列化
* 修改记录:修改类的记录
* 修改人:修改此类的人名称
* 版 本 号:v1.0.0
**********************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ECharts.Series;


namespace ECharts.Utility
{
    public class EnumListConverter<T> : JsonConverter where T:struct, IConvertible
    {
        public EnumListConverter():base()
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type");
            }
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(List<T>);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var enumList = new List<T>();
            var jArray = serializer.Deserialize<JArray>(reader);
            foreach(var item in jArray)
            {
                var enumItem=(T)Enum.Parse(typeof(T), item.ToString());
                enumList.Add(enumItem);
            }
            return enumList;
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var jArray = new JArray();
            foreach(T item in value as List<T>)
            {
               jArray.Add(Enum.GetName(item.GetType(),item));
            }

            jArray.WriteTo(writer);
        }
    }
}
